package com.cnctema.easecalendar_weekly_view.adapters

import android.os.Bundle
import android.util.SparseArray
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentStatePagerAdapter
import com.cnctema.easecalendar_weekly_view.WEEK_START_TIMESTAMP
import com.cnctema.easecalendar_weekly_view.fragments.WeekFragment

/**
 *
 * @ProjectName: EaseCalendar
 * @Description: 周视图
 * @Author: cnctema
 * @CreateDate: 2020/5/24 0:43
 * @Version: 1.0
 */
class WeekPagerAdapter(
    fm:FragmentManager,
    private val mWeekTimestamps: List<Long>,
    private val mListener: WeekFragment.WeekScrollListener
) :FragmentStatePagerAdapter(fm) {
    private val mFragments = SparseArray<WeekFragment>()

    override fun getCount(): Int = mWeekTimestamps.size

    override fun getItem(position: Int): Fragment {
        val bundle = Bundle()
        val weekTimestamp = mWeekTimestamps[position]
        bundle.putLong(WEEK_START_TIMESTAMP,weekTimestamp)

        val fragment = WeekFragment()
        fragment.arguments = bundle
        fragment.setListener(mListener)

        mFragments.put(position,fragment)
        return fragment
    }

    // 更新Y轴滑动位置
    fun updateScrollY(pos: Int, y: Int) {
        (-1..1).map { mFragments[pos + it] }
            .forEach { it?.updateScrollY(y) }
    }
}
